# coding=utf8

from django.contrib import admin
from django.core.files.base import ContentFile
from tussin.news.models import Article, Category
from tussin.news.forms import ArticleForm
import datetime

class CategoryAdmin(admin.ModelAdmin):
    fields = ('name', 'order', 'parent', 'editors')
    list_filter = ('name', 'parent')
    ordering = ['id']
    #filter_horizontal = ('editors',)

    def queryset(self, request):
        qs = super(CategoryAdmin, self).queryset(request)
        return qs.filter(id__gte=2)

class ArticleAdmin(admin.ModelAdmin):
    form = ArticleForm
    list_display = ('title', 'category', 'editor', 'status',  'is_headline', 'created', 'updated')
    list_filter = ('category', 'status')
    search_fields = ('title', 'content')
    ordering = ['-created']
    fields = ('title', 'category', 'is_headline', 'headline_image','source', 'summary', 'content')
    actions = ['make_published']

    def queryset(self, request):
        qs = super(ArticleAdmin, self).queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(category__in=request.user.category_set.all())

    def save_model(self, request, obj, form, change):
        if not change:
            obj.editor = request.user
        if request.method == "POST":
            form = ArticleForm(request.POST, request.FILES)
            if form.is_valid():
                file = ContentFile(request.FILES['headline_image'].read())
                #filename = unicode(request.FILES['headline_image'].name, errors='ignore')
                filename = request.FILES['headline_image'].name
                obj.headline_image.save(filename, file)
        obj.save()

    def make_published(self, request, queryset):
        if request.user.has_perm('news.make_published'):
            row_updated = queryset.update(status=2, updated=datetime.datetime.now())
            msg = "成功发布%s篇文章" % row_updated
        else:
            msg = "你没有发布文章的权限，请联系管理员。"
        self.message_user(request, msg)
    make_published.short_description = u"发布所选的 文章"

    class Media:
        #js = ('ckeditor/ckeditor.js','tinymce/tiny_mce.js','/static/js/myadmin.js',)
        js = ('/static/tinymce/tiny_mce.js','/static/js/myadmin.js',)

admin.site.register(Category, CategoryAdmin)
admin.site.register(Article, ArticleAdmin)
